package C027;

import java.util.ArrayList;
import java.util.PriorityQueue;

/**
 * ClassName: C01
 * Package: C027
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/12/12 17:48
 * @Version 1.0
 * @Since 1.0
 */
public class C01 {
    static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {


    }
    public static ListNode mergeKLists(ArrayList<ListNode> lists) {
        // write code here
        PriorityQueue<ListNode> heap = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
        ListNode head;
        ListNode cur;
        ListNode pre;
        for (ListNode list : lists) {
            if(null != list){
                heap.add(list);
            }
        }
        if(heap.isEmpty()) {
            return null;
        }
        head = heap.poll();
        cur = head;
        if(head.next != null) {
            heap.add(head.next);
        }
        while (!heap.isEmpty()) {
            pre = heap.poll();
            cur.next = pre;
            cur = cur.next;
            if(pre.next != null) {
                heap.add(pre.next);
            }
        }
        return head;
    }
}
